<?php
namespace Nawa\MedicalStudy;
/**
 * Inquiry Type Object.
 *
 * It represant a type of a sales Order
 *
 * @author Xavier VILAIN
 * @package sales
 * @subpackage inquiry
 *
 * @property int	$id				Id of the line
 * @property int	$inquiryid		Id of the corresponding an Order
 * @property int 	$itemid 		Id of the corresponding Item (0 = Header)
 * @property string $role 			Partner Role
 * @property string $customerid 	Id of Customer Partner
 * 
 * @method \Nawa\MedicalStudy medicalStudy() Retrieve Corresponding Medical Study Object
 * @method \Nawa\Customer customer() Retrieve customer Object
 * @method array medicalCentersLinks() Retrieve all medical centers associate to a partner
 * 
 */
use Fox\Dao\SqlFragment;

class Partner extends \Fox\Object {

	/**
	 * Link to Medical Study
	 */
	const LINK_MEDICAL_STUDY = 'medicalStudy';

	/**
	 * Link to a Customer
	 */
	const LINK_CUSTOMER = 'customer';
	
	/**
	 * Link to Medical Center Links (MedicalStudy\MedicalCenter\Partner)
	 */
	const LINK_MEDICAL_CENTERS_LINKS = 'medicalCentersLinks';

	/**
	 * Link to Medical Study
	 */
	const LINK_MEDICAL_STUDIES = 'medicalStudies';

	/**
	 *
	 * Get id of the partner according to the parnter type
	 */
	public function partnerid()
	{
		return $this->customerid;
	}

	/**
	 * Unique Id in sales objects
	 */
	public function salesId()
	{
		return $this->role.':'.$this->partnerid();
	}
		
	/**
	 * Find Corresponding User 
	 */
	public function user() {
		$finder = new \User();
		$res = $finder->find(new SqlFragment('prfnm = ? AND prfvl = ?',
						array(\User::PREFERENCE_LINK_TO_CONTACT,$this->partnerid())),
						null,
						array(\User::$JOIN_PREFERENCES));
		if(count($res) == 1) {
			return $res[0];
		} else {
			return false;
		}
	}
	
	/**
	 * (non-PHPdoc)
	 * @see Fox.Object::delete()
	 */
	public function delete() {
		$handle = \Fox\Dao::infos(self::className())->handle();
		$handle->beginTransaction();
		// Remove MS-MC links
		foreach($this->medicalCentersLinks() as $centerLink)
		{
			$centerLink->delete();
		}
		parent::delete();
		$handle->commit();
	}
	
}
\Fox\Dao::infos(
Partner::className(),
new \Fox\Object\Info('ms_partners', \Fox\Databases::DB_APP)
)->addAutoIncrementField('id');

// Link to Customer
\Fox\Object\Links::add(\Fox\Dao::link(MedicalCenter\Partner::className(), MedicalCenter\Partner::LINK_MEDICAL_STUDIES_PARTNER)
->to(Partner::className(), Partner::LINK_MEDICAL_CENTERS_LINKS)
->on('msid','customerid')
);